package com.ruoqing.admin.api.impl;

import com.ruoqing.admin.api.AuthService;
import com.ruoqing.core.constant.Constants;
import com.ruoqing.core.constant.Oauth2ModeConstants;
import com.ruoqing.core.dto.auth.AuthDto;
import com.ruoqing.core.dto.auth.LoginUserDto;
import com.ruoqing.core.vo.auth.AuthResponseVo;
import com.ruoqing.redis.dto.UserAuthorityDto;
import com.ruoqing.system.rest.Oauth2UserLogin;
import com.ruoqing.utils.common.RedisUtils;
import com.ruoqing.utils.common.ServletUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
	* @author YaoXian
	* @title: AuthServiceImpl
	* @projectName ruoxi-blog
	* @description: 若兮微服务 - 统一认证与授权 - 业务层实现类
	* @date 2020-12-18 14:11
	*/
@Service
@RefreshScope
public class AuthServiceImpl implements AuthService {
		
		@Resource
		private Oauth2UserLogin oauth2UserLogin;
		
		@Resource
		private RedisTemplate<String, UserAuthorityDto> redisTemplate;
		
		@Value("${oauth2.client_id}")
		private String clientId;
		
		@Value("${oauth2.client_secret}")
		private String clientSecret;
		
		@Override
		public AuthResponseVo login(LoginUserDto loginUserDto) {
				String msg;
				StringBuffer url = ServletUtils.getRequest().getRequestURL();
				if (url.toString().contains("admin")){
						AuthDto authDto = oauth2UserLogin.getUserToken(
										Oauth2ModeConstants.PASSWORD,
										clientId, clientSecret, loginUserDto);
						if (authDto.getStatus().equals(Constants.responseOk)){
								msg = "登录成功!";
								UserAuthorityDto userAuthorityDto = redisTemplate.boundValueOps(loginUserDto.getUsername()).get();
								redisTemplate.boundValueOps(authDto.getTokenDto().getAccess_token())
												.set(userAuthorityDto);
								return AuthResponseVo.buildAuthResponseVo(authDto.getStatus(),msg,
												authDto.getTokenDto().getAccess_token(),
												userAuthorityDto);
						}else {
								return AuthResponseVo.buildAuthResponseVo(authDto.getStatus(),
												authDto.getMessage());
						}
				}
				RedisUtils.closeRedisConnection(redisTemplate);
				return AuthResponseVo.buildAuthResponseVo(Constants.responseError,"未知错误!");
		}
		
}
